package com.kaiyidiannao.activity.messageInfo;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.*;
import com.kaiyidiannao.activity.login_or_registered.LoginOrRegistered;
import com.kaiyidiannao.activity.user_detail.EditUserDetail;
import com.kaiyidiannao.adapter.MessageAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.common.pulltorefresh_view.DragListView;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.MessageBean;
import com.kaiyidiannao.model.bean.UserBean;
import com.kaiyidiannao.model.req.model.GetMessageInfoLIst;
import com.kaiyidiannao.model.req.model.GetMessageInfoTop;
import com.kaiyidiannao.view.ActionBarView;
import com.kaiyidiannao.view.AutoTextView;
import com.taplinker.core.util.LogUtil;

import java.util.*;

/**
 * Created by wzg on 14-4-14.
 */
public class MessageInfo extends BaseActionBarActivity implements View.OnClickListener, Observer {
    private ArrayList<UserBean> userBeans = DataCenter.userLogin;
    private ArrayList<UserBean> userBeanes = DataCenter.userBeans;
    private ActionBarView actionBarView;
    private ArrayList<MessageBean> targetList = DataCenter.messageInfoList;
    //最新分类样式
    private ListView categoryListView;
    private SimpleAdapter simpleAdapter;
    private List<Map<String, String>> data;
    private View itemParent;
    private DragListView listView;
    private BaseAdapter adapter = null;
    private CheckBox checkbox_category;//展开分类的checkbox
    private View no_content_view;//没有数据的布局对象
    private AutoTextView autoTextView;
    //请求数据参数
    private int catid = DataCenter.messageInfo_id[0];
    private int currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
    private boolean isClose = true;
    private ProgressBar progressBar;
    private String[] categorys = null;
    private DisplayMetrics dm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message_info);

        DataCenter.rolling_current_module_id = DataCenter.moduleFlag.messageInfo;
        // 添加观察者
        DataCenter.getInstance().addObserver(this);
        init();
        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        //获得手机的宽带和高度像素单位为px
        String str = "手机屏幕分辨率为:" + dm.widthPixels
                + " * " + dm.heightPixels;


        findviews();
        //最新分类
        initCategoryData();
        initCategoryView();

        showCurrentProgressView();
        if (userBeanes.size() == 0) {
            new GetMessageInfoLIst(catid, DataCenter.LISTVIEW_DEFAULT_PAGE).execute();
            Log.d("-=-=-=-=-11", "111111111111");
        } else {
            new GetMessageInfoLIst(catid, Integer.parseInt(userBeanes.get(0).getUserid()), DataCenter.LISTVIEW_DEFAULT_PAGE).execute();
            Log.d("-=-=-=-=-11", "222222222222");
        }

        if (!HttpUtils.isConnected()) {

        } else {
            new GetMessageInfoTop(catid).execute();
        }

    }

    @Override
    protected void onRestart() {
        showCurrentProgressView();
//        currentPage = 1;
//        targetList.clear();

        if (userBeanes.size() == 0) {
            new GetMessageInfoLIst(catid, DataCenter.message_position/10+1).execute();
            Log.d("-=-=-=-=-11", "111111111111");
        } else {
            new GetMessageInfoLIst(catid, Integer.parseInt(userBeanes.get(0).getUserid()), DataCenter.message_position/10+1).execute();
            Log.d("-=-=-=-=-11", "222222222222");
        }

        super.onRestart();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.d(DataCenter.LOG_INFO, MessageInfo.class.getSimpleName() + ".onDestroy");
        DataCenter.messageInfoList.clear();
        DataCenter.PAGE = 0;
        //删除观察者
        DataCenter.getInstance().deleteObserver(this);
    }

    private void initCategoryData() {
        data = new ArrayList<Map<String, String>>();

        TreeMap<String, String> map = null;

        categorys = getResources().getStringArray(R.array.messageInfo);

        for (int i = 0; i < categorys.length; ++i) {
            map = new TreeMap<String, String>();
            if (i == 0) {
                map.put("img", "" + DataCenter.commmon_category_img[0]);
            } else {
                map.put("img", "" + DataCenter.commmon_category_img[1]);
            }
            map.put("title", categorys[i] + "...");
            data.add(map);
        }
    }

    private void initCategoryView() {
        categoryListView = (ListView) findViewById(R.id.category_listview);

        String[] from = new String[]{"img", "title"};
        int[] to = new int[]{R.id.category_icon, R.id.category_title};
        simpleAdapter = new SimpleAdapter(this, data, R.layout.category_listview_item, from, to);
        categoryListView.setAdapter(simpleAdapter);
        categoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                itemParent = view;
                catid = DataCenter.messageInfo_id[i];
                TextView textview = (TextView) itemParent.findViewById(R.id.category_title);
                textview.setTextColor(getResources().getColor(R.color.title_detail_color));
                simpleAdapter.notifyDataSetChanged();

                DataCenter.playTopBeansTopList.clear();
                currentPage = 1;
                actionBarView.title.setText(categorys[i]);
                isClose = true;
                closeTopBar();
                if (userBeanes.size() == 0) {
                    new GetMessageInfoLIst(catid, currentPage).execute();
                } else {
                    new GetMessageInfoLIst(catid, Integer.parseInt(userBeanes.get(0).getUserid()), currentPage).execute();
                }
                new GetMessageInfoTop(catid).execute();
            }
        });
    }


    @Override
    protected void openTopBar() {
        actionBarView.setTitleIconIsUp(true);

        initCategoryView();

        categoryListView.setVisibility(View.VISIBLE);
        categoryListView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.top_bar_in));
    }

    @Override
    protected void closeTopBar() {
        actionBarView.setTitleIconIsUp(false);
        categoryListView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.top_bar_out));
        categoryListView.setVisibility(View.GONE);
    }


    @Override
    protected boolean isShownTopBar() {
        return categoryListView.getVisibility() == View.VISIBLE;
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
            if (isShownTopBar()) {
                actionBarView.checkBox.setChecked(false);
                isClose = true;
                closeTopBar();
                return false;
            }
        }
        return super.dispatchKeyEvent(event);
    }


    public void init() {
//        VerticalViewPager mViewPager = (VerticalViewPager) findViewById(R.id.viewpager);
//        mViewPager.setAdapter(new MyPagerAdapter(this));
//        AutoUpTextView scheduler = new AutoUpTextView(mViewPager);
//        scheduler.updateCount(6);//有几个轮播项
//        scheduler.restart(2000);//轮播间隔

        actionBarView = (ActionBarView) findViewById(R.id.infoActionBar);
        actionBarView.button_right_icon2.setVisibility(View.VISIBLE);
        actionBarView.button_right_icon2.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.publish));
        actionBarView.button_right_icon2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userBeans.size() == 0) {
                    Intent intent = new Intent(MessageInfo.this, LoginOrRegistered.class);
                   // intent.putExtra("ClassName", MessageInfo.class.getName());
                    startActivity(intent);
                  //  Log.d("classname", MessageInfo.class.getName());
                    Toast.makeText(MessageInfo.this, "请先登录", Toast.LENGTH_SHORT).show();
                   // finish();
                } else if (userBeanes.get(0).getUsername() == null || userBeanes.get(0).getUsername().equals("")) {
                    Intent intent = new Intent(MessageInfo.this, EditUserDetail.class);
                   // intent.putExtra("ClassName", MessageInfo.class.getName());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(MessageInfo.this, MessagePublish.class);
                    startActivity(intent);
                }
            }
        });
        findActionBar();
    }

    private void findActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.infoActionBar);
        actionBarView.setTitle("分类");
        actionBarView.setTitleOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isClose = !isClose;
                if (isClose) {
                    closeTopBar();
                } else { //开启分类条
                    openTopBar();
                }
            }
        });
        actionBarView.checkBox.setVisibility(View.GONE);
        actionBarView.setTitleIconIsUp(false);

        checkbox_category = actionBarView.checkBox;
        checkbox_category.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isShownTopBar()) {
                    closeTopBar();
                } else {
                    openTopBar();
                }
                checkbox_category.setChecked(isShownTopBar());
            }
        });

        actionBarView.setTitleIconIsUp(false);
    }

    private void findviews() {
        autoTextView = (AutoTextView) findViewById(R.id.switcher02);
        progressBar = (ProgressBar) findViewById(R.id.play_inner_progress_bar);
        no_content_view = findViewById(R.id.no_content_view);
        adapter = new MessageAdapter(this, targetList);
        listView = (DragListView) findViewById(R.id.messageInfo_List);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundleData = new Bundle();
                bundleData.putSerializable("playBean", targetList.get(position - 1));
                Class<?> classz = MessageInfoDetail.class;
                Intent intent = new Intent(MessageInfo.this, classz);
                intent.putExtras(bundleData);
                intent.putExtra("itemid", targetList.get(position - 1).getItemid() + "");
                intent.putExtra("catid", targetList.get(position - 1).getCatid() + "");
                startActivity(intent);
                DataCenter.message_position = position-1;
                DataCenter.PAGE = (position-1)/10+1;
                currentPage = (position-1)/10+1;
            }
        });
        adapter.notifyDataSetChanged();
        listView.setOnRefreshListener(new DragListView.OnRefreshLoadingMoreListener() {
            @Override
            public void onRefresh() {//表示搜索框开启
                if (userBeanes.size() == 0) {
                    new GetMessageInfoLIst(catid, DataCenter.LISTVIEW_DEFAULT_PAGE).execute();
                } else {
                    new GetMessageInfoLIst(catid, Integer.parseInt(userBeanes.get(0).getUserid()), DataCenter.LISTVIEW_DEFAULT_PAGE).execute();
                }

                new GetMessageInfoTop(catid).execute();
                currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;

            }

            @Override
            public void onLoadMore() {
                if (userBeanes.size() == 0) {
                    new GetMessageInfoLIst(catid, ++currentPage).execute();
                } else {
                    new GetMessageInfoLIst(catid, Integer.parseInt(userBeanes.get(0).getUserid()), ++currentPage).execute();
                }
                //adapter.notifyDataSetChanged();

            }
        });

        progressBar = (ProgressBar) findViewById(R.id.play_inner_progress_bar);
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;
        if (!HttpUtils.isConnected()) {
            listView.onRefreshComplete();
            listView.onLoadMoreComplete(false);
        }
        if (!HttpUtils.isConnected()) {
            progressBar.setVisibility(View.GONE);
            no_content_view.setVisibility(View.VISIBLE);
        }
        if (flag == DataCenter.flag.GET_MESSAGEINFO_SUCCESS
                || flag == DataCenter.flag.GET_MESSAGEINFO_FAILED) { //类表数据
            progressBar.setVisibility(View.GONE);
            listView.onRefreshComplete();
            listView.onLoadMoreComplete(false);
            adapter.notifyDataSetChanged();

            if (flag == DataCenter.flag.GET_MESSAGEINFO_SUCCESS) {
                Log.d(DataCenter.LOG_INFO, " DdcListActivity.update() -> SUCCESS");
                if ((targetList == null || targetList.size() < 1)) {
                    no_content_view.setVisibility(View.VISIBLE);
                    listView.setVisibility(View.INVISIBLE);
                    ((TextView) no_content_view.findViewById(R.id.notice_msg_tv)).setText(getText(R.string.listview_msg_empty));
                } else {
                    listView.setVisibility(View.VISIBLE);
                    no_content_view.setVisibility(View.GONE);
                }

            }

            if (flag == DataCenter.flag.GET_MESSAGEINFO_FAILED) {
                if (targetList.size() < 1) {
                    no_content_view.setVisibility(View.VISIBLE);
                    listView.setVisibility(View.INVISIBLE);
                    ((TextView) no_content_view.findViewById(R.id.notice_msg_tv)).setText(getText(R.string.listview_msg_error));
                } else {
                    no_content_view.setVisibility(View.GONE);
                }
                Log.d(DataCenter.LOG_ERROR, " PlayListActivity.update() -> FAILED");
            }

            closeProgressDialog();
        } else if (flag == DataCenter.flag.GET_MESSAGEINFO_TOP_SUCCESS) { // 置顶滚动栏数据
            ArrayList<MessageBean> topBeanList = DataCenter.messageInfoTop;
            autoTextView.setData3(topBeanList);
            autoTextView.startRolling();
        }
    }

    @Override
    public void onClick(View v) {

    }


    /**
     * 显示列表数据
     */
    private void showCurrentDataView() {
        listView.setVisibility(View.VISIBLE);
        no_content_view.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 正在加载，隐藏列表
     */
    private void showCurrentProgressView() {
        listView.setVisibility(View.GONE);
        no_content_view.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);
    }

    /**
     * 提示没有数据
     */
    private void showCurrentEmptyMsgView() {
        listView.setVisibility(View.GONE);
        ((TextView) no_content_view.findViewById(R.id.notice_msg_tv)).setText(getText(R.string.listview_msg_empty));
        no_content_view.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
    }
}
